package cn.edu.tsinghua.weibo.util;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.tsinghua.weibo.entity.User;

import net.sf.json.JSONObject;

@SuppressWarnings("serial")
public class ImageCrop extends HttpServlet {

	private final static String SQL = "update user set avatar=? where id=?";
	private final static double LENGTH = 300.0;
	private final static double AVATAR_SIZE = 180;
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		
//		取得坐标xy，剪裁长宽wh，上传原始文件名file
		int x = Integer.parseInt(request.getParameter("x"));
		int y = Integer.parseInt(request.getParameter("y"));
		int w = Integer.parseInt(request.getParameter("w"));
		int h = Integer.parseInt(request.getParameter("h"));
		String file = request.getParameter("f");
//System.out.println(x+", "+y+", "+w+", "+h);

//		读取上传的原始头像
		String context = this.getServletConfig().getServletContext().getRealPath("/");
		String rawavatar = context + "uploads/" + file;
		BufferedImage rawimage = ImageIO.read(new File(rawavatar));
		
		double width = rawimage.getWidth();
		double height = rawimage.getHeight();
//System.out.println("width:" + width + ", height:" + height);
		
		double longside = (width>height)?width:height;
//System.out.println("longside:" + longside);

		if(longside>LENGTH) {
//System.out.println("---------->" + longside/LENGTH);
			w *= (longside/LENGTH);
			h *= (longside/LENGTH);
			
			x *= (longside/LENGTH);
			y *= (longside/LENGTH);
		}
//System.out.println(x+", "+y+", "+w+", "+h);
		w = (int) ((x+w>width)?(width-x):w);
		h = (int) ((y+h>height)?(height-y):h);
//System.out.println(x+", "+y+", "+w+", "+h);
		
//		剪裁生成新头像
		BufferedImage croppedimage = rawimage.getSubimage(x, y, w, h);//subString
		
//		缩放
//		生成处理后的图片存储空间。  
        BufferedImage changedImage = new BufferedImage((int)AVATAR_SIZE, (int)AVATAR_SIZE, BufferedImage.TYPE_3BYTE_BGR);  
  
//      缩放比例。  
        double widthBo = AVATAR_SIZE/w;  
        double heightBo = AVATAR_SIZE/h;  
//System.out.println(widthBo);
        AffineTransform transform = new AffineTransform();  
        transform.setToScale(widthBo, heightBo);  
  
//      根据剪裁后的图片生成缩放后的图片
        AffineTransformOp ato = new AffineTransformOp(transform, null);  
        ato.filter(croppedimage, changedImage);  

//		取得上传文件扩展名
		String extname = "";
		if (file.lastIndexOf(".") >= 0) {
			extname = file.substring(file.lastIndexOf("."));
		}

//		保存新头像到avatar目录
		String savePath = context + "avatar/";
		String newavatar = Long.toString(System.nanoTime()) +extname;
		ImageIO.write(changedImage, "jpg", new File(savePath + newavatar)); 
		
//		取得userid
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		int userid = user.getId();

//		更新数据库avatar字段
		Connection connection = DB.getConnection();
		PreparedStatement preparedStatement = null;
		try {
			preparedStatement = connection.prepareStatement(SQL);
			preparedStatement.setString(1, newavatar);
			preparedStatement.setInt(2, userid);
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		DB.close(preparedStatement, connection);

//		重设session中user的avatar值
		user.setAvatar(newavatar);
		session.setAttribute("user", user);
		
//		返回status：ok
		Map<String, String> map =  new HashMap<String, String>();
		map.put("status", "ok");
		JSONObject jsonObject = JSONObject.fromObject(map);
		response.setContentType("text/html; charset=utf-8");
		response.getWriter().print(jsonObject);
	}

}